package gov.pbc.nn.kjgl.item.template.service;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.util.proxy.ProxyBeanUtils;

import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.kjgl.item.template.ItemApprovalWarpper;
import gov.pbc.nn.kjgl.item.template.ItemApprovalWarpper.AcceptDeptWarpper;
import gov.pbc.nn.kjgl.item.template.entity.AbstractItem;
import gov.pbc.nn.kjgl.item.template.entity.AcceptDept;
import gov.pbc.nn.kjgl.item.template.entity.ItemApproval;
import gov.pbc.nn.kjgl.item.template.view.ItemApprovalPR;

@Component
public abstract class AbstractItemService {

	public abstract void saveItem(AbstractItem item) throws Exception;

	@Resource(name = CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao hibernateDao;

	@DataResolver
	@Transactional
	public ItemApproval save(AbstractItem item, String tmpFilename) throws Exception {
		this.saveItem(item);
		return this.saveTemplateItem(item, tmpFilename);
	}

	private ItemApproval saveTemplateItem(AbstractItem item, String tmpFilename) throws Exception {
		Path path = Paths.get(System.getProperty("java.io.tmpdir"), tmpFilename);
		try (FileInputStream fin = new FileInputStream(path.toFile());) {
			ObjectInputStream is = new ObjectInputStream(fin);
			ItemApprovalWarpper iaw = (ItemApprovalWarpper) is.readObject();
			ItemApproval ia = iaw.getItem();
			EntityState state = iaw.getState();
			if (state == EntityState.NEW) {
				ia.setBusEntityClass(ProxyBeanUtils.getProxyTargetType(item.getClass()).getName());
				ia.setBusKey(item.getId());
				ia.setState(0);
				this.hibernateDao.save(ia);
			} else if (state == EntityState.MODIFIED) {
				this.hibernateDao.update(ia);
			}
			for (AcceptDeptWarpper adw : iaw.getDepts()) {
				state = adw.getState();
				AcceptDept ad = adw.getDept();
				if (state == EntityState.NEW) {
					ad.setItemApprovalId(ia.getId());
					this.hibernateDao.save(ad);
				}
			}
			ItemApprovalPR iaPR = ContextHolder.getBean("itemApprovalPR");
			return iaPR.loadItem(ia.getId());
		}
	}

}
